package com.hhh.springai_test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhh.springai_test.common.ErrorCode;
import com.hhh.springai_test.constant.UserConstant;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.mapper.CommentReplyMapper;
import com.hhh.springai_test.model.dto.commentreply.AddCommentReplyDTO;
import com.hhh.springai_test.model.dto.commentreply.QueryCommentReplyDTO;
import com.hhh.springai_test.model.dto.commentreply.UpdateCommentReplyDTO;
import com.hhh.springai_test.model.po.CommentReply;
import com.hhh.springai_test.model.po.User;
import com.hhh.springai_test.model.vo.CommentReplyVO;
import com.hhh.springai_test.model.vo.UserVo;
import com.hhh.springai_test.service.CommentReplyService;
import com.hhh.springai_test.service.UserService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author 29915
* @description 针对表【comment_reply(评论回复表)】的数据库操作Service实现
* @createDate 2025-02-06 09:28:13
*/
@Service
public class CommentReplyServiceImpl extends ServiceImpl<CommentReplyMapper, CommentReply>
    implements CommentReplyService {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String REPLY_LOCK_KEY = "reply:lock:";

    @Override
    public Long addCommentReply(AddCommentReplyDTO addCommentReplyDTO, Long userId) {
        if (addCommentReplyDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 不能给自己回复评论
        if (userId.equals(addCommentReplyDTO.getReplyUserId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不能给自己回复评论");
        }

        // 获取锁
        String lockKey = REPLY_LOCK_KEY + userId;
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 5, TimeUnit.SECONDS);
        if (Boolean.FALSE.equals(lock)) {
            throw new BusinessException(ErrorCode.BUSY_ERROR, "操作太频繁");
        }

        try {
            CommentReply commentReply = new CommentReply();
            commentReply.setCommentid(addCommentReplyDTO.getCommentId());
            commentReply.setUserid(userId);
            commentReply.setReplyuserid(addCommentReplyDTO.getReplyUserId());
            commentReply.setContent(addCommentReplyDTO.getContent());
            commentReply.setReplytime(new Date());
            boolean success = this.save(commentReply);
            if (!success) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "回复保存失败");
            }

            return commentReply.getId();
        } finally {
            // 释放锁
            redisTemplate.delete(lockKey);
        }
    }

    @Override
    public boolean deleteCommentReply(Long id, Long userId) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        CommentReply commentReply = this.getById(id);
        if (commentReply == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "评论不存在");
        }

        User user = userService.getById(userId);
        if (!userId.equals(commentReply.getUserid()) && !user.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            throw new BusinessException(ErrorCode.NOT_AUTH_CODE, "你没有权限删除此条评论");
        }

        return this.removeById(id);
    }

    @Override
    public boolean updateCommentReply(UpdateCommentReplyDTO updateCommentReplyDTO, Long userId) {
        if (updateCommentReplyDTO == null || updateCommentReplyDTO.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        CommentReply commentReply = this.getById(updateCommentReplyDTO.getId());
        if (commentReply == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该评论不存在");
        }

        User user = userService.getById(userId);
        if (!userId.equals(commentReply.getUserid()) && !user.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            throw new BusinessException(ErrorCode.NOT_AUTH_CODE, "你没有权限删除此条评论");
        }

        CommentReply updateReply = new CommentReply();
        updateReply.setId(updateCommentReplyDTO.getId());
        updateReply.setContent(updateCommentReplyDTO.getContent());
        updateReply.setUpdatetime(new Date());

        return this.updateById(updateReply);
    }

    @Override
    public Page<CommentReplyVO> queryCommentReplyPage(QueryCommentReplyDTO queryCommentReplyDTO) {
        if (queryCommentReplyDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        LambdaQueryWrapper<CommentReply> queryWrapper = new LambdaQueryWrapper<>();
        if (queryCommentReplyDTO.getCommentId() != null) {
            queryWrapper.eq(CommentReply::getCommentid, queryCommentReplyDTO.getCommentId());
        }
        queryWrapper.like(StringUtils.isNotBlank(queryCommentReplyDTO.getContent()), 
                         CommentReply::getContent, 
                         queryCommentReplyDTO.getContent());
        queryWrapper.orderByDesc(CommentReply::getCreatetime);

        // 获取分页大小，默认为10
        long pageSize = queryCommentReplyDTO.getPageSize() != null ? queryCommentReplyDTO.getPageSize() : 10;
        Page<CommentReply> replyPage = this.page(new Page<>(queryCommentReplyDTO.getCurrent(), pageSize), queryWrapper);
        
        // 转换为VO
        Page<CommentReplyVO> replyVOPage = new Page<>(replyPage.getCurrent(), replyPage.getSize(), replyPage.getTotal());
        List<CommentReplyVO> replyVOList = replyPage.getRecords().stream().map(reply -> {
            CommentReplyVO replyVO = new CommentReplyVO();
            BeanUtils.copyProperties(reply, replyVO);
            
            // 获取回复用户信息
            User user = userService.getById(reply.getUserid());
            if (user != null) {
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);
                replyVO.setUserInfo(userVo);
            }
            
            // 获取被回复用户信息
            User replyUser = userService.getById(reply.getReplyuserid());
            if (replyUser != null) {
                UserVo replyUserVo = new UserVo();
                BeanUtils.copyProperties(replyUser, replyUserVo);
                replyVO.setReplyUserInfo(replyUserVo);
            }
            
            return replyVO;
        }).collect(Collectors.toList());
        
        replyVOPage.setRecords(replyVOList);
        return replyVOPage;
    }
}




